package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 菜品管理
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorsMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 菜品分页查询
     * @param dto
     * @return
     */

    @Override
    public PageResult queryByPage(DishPageQueryDTO dto) {
        //使用分页插件
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //获得分页查询结果，调用查询方法
        List<DishVO> dishVOList= dishMapper.selectByPage(dto);
        Page p = (Page) dishVOList;

        return new PageResult(p.getTotal(),p.getResult());
    }


    /**
     * 新增菜品功能
     * @param dto
     */
    @Override
    @Transactional
    public void save(DishDTO dto) {
        //补齐数据，创建时间，更新时间，创建人，更新人
        Dish dish=new Dish();
        BeanUtils.copyProperties(dto,dish);
        dish.setStatus(StatusConstant.ENABLE);
//        dish.setCreateTime(LocalDateTime.now());
//        dish.setUpdateTime(LocalDateTime.now());
//        dish.setCreateUser(BaseContext.getCurrentId());
//        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.insert(dish);


        //同时新增菜品口味
        Long dishId = dish.getId();
        log.info("获取的菜品id是：{}",dishId);
        List<DishFlavor> flavors = dto.getFlavors();
        //如果口味集合不是空就新增
        if (flavors != null && flavors.size()>0) {
            flavors.forEach(flavor ->{
                flavor.setDishId(dishId);
            });
            dishFlavorMapper.insert(flavors);
        }
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO queryById(Long id) {
        Dish dish= dishMapper.selectByDishId(id);

        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectById(id);
        DishVO dishVO = new DishVO();

        //将查询到的数据封装到VOv
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }


    /**
     * 修改菜品
     * @param dto
     */

    @Override
    @Transactional
    public void dishUpdate(DishDTO dto) {
        //开启事务管理，先删除甜度表，再把接收的信息放入菜品表和甜度表
        //先查询不为空再删

        Dish dish =new Dish();
        BeanUtils.copyProperties(dto,dish);
        Long id = dto.getId();
        List<DishFlavor> dishFlavors= dishFlavorMapper.selectById(id);
        if (dishFlavors != null && dishFlavors.size() >0) {
            dishFlavorMapper.delete(id);
        }

        //修改菜品同时修改菜品与套餐关系表中的菜品名
        setmealDishMapper.update(dto);

        //新增甜度关联
        //先判断传进来的甜度信息不为空再新增
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && flavors.size()>0) {
            flavors.forEach(flavor ->{
                flavor.setDishId(id);
            });
            dishFlavorMapper.insert(flavors);
        }

        //更新菜品信息
        dishMapper.update(dish);


    }

    /**
     * 修改菜品状态
     * @param status
     * @param id
     */
    @Override
    @Transactional
    public void statusChange(Integer status, Long id) {
        //修改菜品状态，在mapper层添加aop注解自动设置修改时间和修改人
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        //菜品停售，则包含该菜品的套餐也要停售

        if (status == StatusConstant.DISABLE) {
            Setmeal setmeal= Setmeal.builder()
                    .status(status)
                    .build();
            setmealMapper.update(setmeal);
        }
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional   // 用事物管理，删除菜品不需要在记录修改人和修改时间
    public void delete(List<Long> ids) {

            List<Long> setmealId= setmealDishMapper.selectSetmealIdsByDishIds(ids);
            if (setmealId != null && setmealId.size() > 0) {
                throw  new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }

        //检查菜品是否是停售状态，不是就提示不能删除
        List<Integer> status=dishMapper.selectStatusByIds(ids);
        for (Integer i : status) {
            if (i == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //排除无法删除情况，开始删除菜品
        dishMapper.delete(ids);

        //删除菜品要同时删除关联的口味表
        dishFlavorMapper.deleteAll(ids);

    }


    /**
     * 根据分类id查询菜品集合
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> queryByCategory(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .build();
        List<Dish> dishs=dishMapper.selectDishByCategoryId(dish);
        //如果菜品停售，就
        for (int i = 0; i < dishs.size(); i++) {
            if (dishs.get(i).getStatus() == 0) {
                dishs.remove(i);
                i--;
            }
        }
        return dishs;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectDishByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
